package com.ruoyi.busi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.busi.domain.BusiCompanyQuota;
import com.ruoyi.busi.domain.bo.BusiCompanyQuotaBo;
import com.ruoyi.busi.domain.vo.BusiCompanyQuotaVo;
import com.ruoyi.busi.mapper.BusiCompanyQuotaMapper;
import com.ruoyi.busi.service.IBusiCompanyQuotaService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractException;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.concurrent.TimeoutException;

/**
 * 企业配额Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-24
 */
@Service
public class BusiCompanyQuotaServiceImpl extends ServicePlusImpl<BusiCompanyQuotaMapper, BusiCompanyQuota, BusiCompanyQuotaVo> implements IBusiCompanyQuotaService {

    @Resource
    private Contract contract;

    @Override
    public BusiCompanyQuotaVo queryById(Long id) {
        return getVoById(id);
    }

    @Override
    public TableDataInfo<BusiCompanyQuotaVo> queryPageList(BusiCompanyQuotaBo bo) {
        PagePlus<BusiCompanyQuota, BusiCompanyQuotaVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<BusiCompanyQuotaVo> queryList(BusiCompanyQuotaBo bo) {
        return listVo(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<BusiCompanyQuota> buildQueryWrapper(BusiCompanyQuotaBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BusiCompanyQuota> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCompanyId() != null, BusiCompanyQuota::getCompanyId, bo.getCompanyId());
        lqw.eq(StringUtils.isNotBlank(bo.getYear()), BusiCompanyQuota::getYear, bo.getYear());
        lqw.eq(bo.getQuota() != null, BusiCompanyQuota::getQuota, bo.getQuota());
        return lqw;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(BusiCompanyQuotaBo bo) {
        BusiCompanyQuota add = BeanUtil.toBean(bo, BusiCompanyQuota.class);
        validEntityBeforeSave(add);
        boolean flag = save(add);

        byte[] queryAResultBefore = new byte[0];
        String desc = "环保局向企业(" + add.getCompanyName() + ")下发" + add.getYear() + "年度排放配额:" + add.getQuota() + "(吨)";
        try {
            queryAResultBefore = contract.submitTransaction("CreateAsset",
                add.getId().toString(),
                add.getCompanyId().toString(),
                add.getCompanyName(),
                add.getYear(), "0",
                desc,
                add.getQuota().toString());
            System.out.println("ReadAsset:" + new String(queryAResultBefore, "utf-8"));
        } catch (ContractException | TimeoutException | InterruptedException | UnsupportedEncodingException e) {
            throw new ServiceException("向区块链提交数据失败,请检查区块链网络是否正常!");
        }

        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(BusiCompanyQuotaBo bo) {
        BusiCompanyQuota update = BeanUtil.toBean(bo, BusiCompanyQuota.class);
        validEntityBeforeSave(update);

        byte[] queryAResultBefore = new byte[0];
        String desc = "环保局向企业(" + update.getCompanyName() + ")重新下发" + update.getYear() + "年度排放配额:" + update.getQuota() + "(吨)";
        try {
            queryAResultBefore = contract.submitTransaction("CreateAsset",
                update.getId().toString(),
                update.getCompanyId().toString(),
                update.getCompanyName(),
                update.getYear(), "0",
                desc,
                update.getQuota().toString());
            System.out.println("ReadAsset:" + new String(queryAResultBefore, "utf-8"));
        } catch (ContractException | TimeoutException | InterruptedException | UnsupportedEncodingException e) {
            throw new ServiceException("向区块链提交数据失败,请检查区块链网络是否正常!");
        }
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(BusiCompanyQuota entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }
}
